package cn.zzszxyy.hr.service;

import cn.zzszxyy.hr.model.RoleEntity;
import cn.zzszxyy.hr.model.RoleMenuEntity;
import cn.zzszxyy.hr.repository.RoleMenuRepository;
import cn.zzszxyy.hr.repository.RoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 作者:张伟
 * <p>
 * 联系:adamzzww@163.com
 * 时间:2016-11-27
 * 说明:角色管理
 */
@Service
public class RoleService {

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private RoleMenuRepository roleMenuRepository;

    public List<RoleEntity> findAll() {
        return roleRepository.findAll();
    }

    public RoleEntity findOne(int id) {
        return roleRepository.findOne(id);
    }

    public Page<RoleEntity> findAllWithPage(int pageIndex, int pageSize) {
        PageRequest pageRequest = new PageRequest(--pageIndex, pageSize);
        Page<RoleEntity> roleList = roleRepository.findAll(pageRequest);
        return roleList;
    }

    @Transactional
    public RoleEntity save(RoleEntity roleEntity, String menuList) {
        // 删除 role 关联表
        roleMenuRepository.deleteByRoleId(roleEntity.getRoleId());

        // 插入菜单信息
        String[] menuArr = menuList.split(";");
        if (menuArr.length > 0) {
            for (String menuId : menuArr) {
                RoleMenuEntity entity = new RoleMenuEntity();
                entity.setMenuId(Integer.parseInt(menuId));
                entity.setRoleId(roleEntity.getRoleId());
                entity.setCreator(roleEntity.getCreator());
                entity.setCreateTime(new Date());
                roleMenuRepository.save(entity);
            }
        }

        // 插入角色信息
        return roleRepository.save(roleEntity);
    }

    @Transactional
    public void delete(int id) {
        //删除：关联表数据
        roleMenuRepository.deleteByRoleId(id);
        //删除：本表记录
        roleRepository.delete(id);
    }

}
